package com.liujit.bms.pc.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liujit.bms.pc.domain.model.BlogLabel;
import com.liujit.bms.pc.domain.result.BlogLabelResult;
import com.liujit.bms.pc.mapper.BlogLabelMapper;
import com.liujit.bms.pc.service.BlogLabelService;
import com.liujit.common.constants.GlobalConstant;
import com.liujit.common.exception.DataNotFoundException;
import com.liujit.common.utils.DozerConvertor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @Description 博客标签Service实现类
 * @Author liujun
 * @Date 2021-07-03 16:18:31
 */
@Service
public class BlogLabelServiceImpl extends ServiceImpl<BlogLabelMapper, BlogLabel> implements BlogLabelService {

    @Override
    public List<BlogLabelResult> getList() {
        List<BlogLabelResult> result = new ArrayList<>();
        LambdaQueryWrapper<BlogLabel> wrapper = new LambdaQueryWrapper();
        wrapper.eq(BlogLabel::getEnabled, GlobalConstant.ENABLED_YES);
        List<BlogLabel> list = super.list(wrapper);
        for (BlogLabel blogLabel : list) {
            BlogLabelResult blogLabelResult = DozerConvertor.convertor(blogLabel, BlogLabelResult.class);
            blogLabelResult
                    .setStyle("font-size: " + RandomUtil.randomInt(12, 22) + "px; color: #" + this.randomHexStr(6));
            result.add(blogLabelResult);
        }
        return result;
    }

    @Override
    public BlogLabelResult get(Long id) {
        BlogLabel blogLabel = super.getById(id);
        if (blogLabel == null) {
            throw new DataNotFoundException();
        }
        return DozerConvertor.convertor(blogLabel, BlogLabelResult.class);
    }

    private String randomHexStr(int len) {
        try {
            StringBuffer result = new StringBuffer();
            for (int i = 0; i < len; i++) {
                // 随机生成0-15的数值并转换成16进制
                result.append(Integer.toHexString(new Random().nextInt(16)));
            }
            return result.toString().toUpperCase();
        } catch (Exception e) {
            log.error("获取16进制字符串异常，返回默认...");
            return "00CCCC";
        }
    }
}
